//
//  TimeView.m
//  OperationPro
//
//  Created by yaxue wang on 2017/2/10.
//  Copyright © 2017年 展鸿科技. All rights reserved.
//

#import "TimeView.h"
#import "LoadingView.h"
@interface TimeView ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, strong)NSMutableArray *typeAr;
@property (nonatomic, strong) void(^action)(NSInteger index);
@property (nonatomic, strong) UIView *boxView;
@property(nonatomic, strong)UIPickerView*pickerView;
@property(nonatomic, strong)NSMutableArray *dataAr;
@property(nonatomic, strong)NSMutableArray *todayAr;
@property(nonatomic, strong)NSMutableArray *timeAr;
@property(nonatomic, strong)NSMutableArray *timeShowAr;
@property(nonatomic, strong)NSString * uuid;
@property (nonatomic, strong)NSString *longitude;
@property (nonatomic, strong)NSString *latitude;
@property (nonatomic, strong)NSString *timeStr;
@property (nonatomic, strong)NSString *hour;

@end
@implementation TimeView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        
    }
    return self;
}

+(TimeView *) showUuid:(NSString *)uuid longitude:(NSString *)longitude latitude:(NSString *)latitude action:(void(^)(NSInteger index))action{
    TimeView *boxView = [[TimeView alloc] init];
    boxView.action = action;
    boxView.uuid=uuid;
    boxView.latitude=latitude;
    boxView.longitude=longitude;
    [boxView showBox];
    return boxView;
}

- (void) initView{
    _timeAr =[[NSMutableArray alloc]init];
    _timeShowAr =[[NSMutableArray alloc]init];
    _dataAr=[[NSMutableArray alloc]init];
    _todayAr=[[NSMutableArray alloc]init];

    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    
    NSString *time=[formatter stringFromDate:date];//@"18:00";//
//    formatter.dateFormat = @"yyyy/MM/dd HH/mm/ss Z";
    NSDate *dta = [[NSDate alloc] init];
    NSDate *dtb = [[NSDate alloc] init];
    
    dta = [formatter dateFromString:time];
    dtb = [formatter dateFromString:@"17:30"];
    NSComparisonResult result = [dta compare:dtb];
    if (result==NSOrderedAscending)
    {
        //日期 时间比17：30小
        for (int i=0; i<5; i++) {
            
            NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
            NSDate* theDate;
            theDate = [date initWithTimeIntervalSinceNow: +oneDay*i];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd";
            NSString *res=[formatter stringFromDate:theDate];
            [_timeAr addObject:res];

            NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
            monthFormatter.dateFormat = @"MM-dd";
            NSString *month=[monthFormatter stringFromDate:theDate];
            
            if (i==0) {
                [_timeShowAr addObject:@"今天"];
            }else if (i==1)
            {
                [_timeShowAr addObject:@"明天"];
                
            }else if (i==2)
            {
                [_timeShowAr addObject:@"后天"];
                
            }else
            {
                [_timeShowAr addObject:[NSString stringWithFormat:@"%@(%@)",month,[self weekdayStringFromDate:theDate]]];
               
                
            }
            
        }
        [_pickerView reloadComponent:0];
//        NSLog(@"=========17：30之前的天数据%@=====%@",_timeShowAr,_timeAr);

        self.timeStr=[_timeAr objectAtIndex:0];//默认今天
        
        //小时
        NSMutableArray*hourAr=[[NSMutableArray alloc]initWithObjects:@"08:00",@"08:30",@"09:00",@"09:30",@"10:00",@"10:30",@"11:00",@"11:30",@"12:00",@"12:30",@"13:00",@"13:30",@"14:00",@"14:30",@"15:00",@"15:30",@"16:00",@"16:30",@"15:00",@"15:30",@"16:00",@"16:30",@"17:00",@"17:30", nil];
        for (int i=0; i<hourAr.count; i++) {
            NSString *hourTime=[hourAr objectAtIndex:i];
            NSDate *dta = [[NSDate alloc] init];
            NSDate *dtb = [[NSDate alloc] init];
            
            dta = [formatter dateFromString:time];
            dtb = [formatter dateFromString:hourTime];
            NSComparisonResult result = [dta compare:dtb];
            if (result==NSOrderedAscending)
            {
                // bDate比aDate大
                [_todayAr addObject:hourTime];
                
            }else {
                
            }
        }
//        NSLog(@"======今天的小时 %@",_todayAr);
        
        [_pickerView reloadComponent:1];
        self.hour=[_todayAr objectAtIndex:0];//默认今天第一行 小时
        
        for (int i=0; i<_timeAr.count; i++) {
            if (i==0) {
                [_dataAr addObject:_todayAr];
            }else
            {
                [_dataAr addObject:hourAr];
                
            }
        }
//        NSLog(@"=========17：30之前的小时组数据%@",_dataAr);

        
    }else {
        //当前时间比17：30大 或者和17:30相等
        //日期
        for (int i=0; i<5; i++) {
            
            NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
            NSDate* theDate;
            theDate = [date initWithTimeIntervalSinceNow: +oneDay*(i+1)];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd";
            NSString *res=[formatter stringFromDate:theDate];
            [_timeAr addObject:res];
            NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
            monthFormatter.dateFormat = @"MM-dd";
            NSString *month=[monthFormatter stringFromDate:theDate];
            if (i==0) {
                [_timeShowAr addObject:@"明天"];
            }else if (i==1)
            {
                [_timeShowAr addObject:@"后天"];
                
            }else
            {
                [_timeShowAr addObject:[NSString stringWithFormat:@"%@(%@)",month,[self weekdayStringFromDate:theDate]]];
                
            }
            
        }
        [_pickerView reloadComponent:0];
        self.timeStr=[_timeAr objectAtIndex:0];//默认明天
//        NSLog(@"======17：30之后的天的数据 %@=====%@",_timeShowAr,_timeAr);

        
        //小时
        NSMutableArray*hourAr=[[NSMutableArray alloc]initWithObjects:@"08:00",@"08:30",@"09:00",@"09:30",@"10:00",@"10:30",@"11:00",@"11:30",@"12:00",@"12:30",@"13:00",@"13:30",@"14:00",@"14:30",@"15:00",@"15:30",@"16:00",@"16:30",@"15:00",@"15:30",@"16:00",@"16:30",@"17:00",@"17:30", nil];
        
        [_pickerView reloadComponent:1];
        self.hour=[hourAr objectAtIndex:0];//默认今天第一行 小时
        
        for (int i=0; i<_timeAr.count; i++) {
          
            [_dataAr addObject:hourAr];
            
        }
//        NSLog(@"=========17：30之后的小时数据%@",_dataAr);

    }

    
   



    UIView *bgView = [[UIView alloc] initWithFrame:self.bounds];
    [self addSubview:bgView];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.6]];
    [bgView bk_whenTapped:^{
        [self hideBox];
    }];
    UIView *whiteView=[[UIView alloc]initWithFrame:CGRectMake(0, WindowHeight/3*2, WindowWidth, WindowHeight/3)];
    whiteView.backgroundColor=[UIColor whiteColor];
    [bgView addSubview: whiteView];
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(45, 0, WindowWidth-90, 40)];
    lab.text=@"预计处理时间";
    lab.font=F(15);
    lab.textAlignment=NSTextAlignmentCenter;
    lab.textColor=[UIColor blackColor];
    [whiteView addSubview:lab];
    UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 40-0.5,WindowWidth, 0.5)];
    line.backgroundColor=C(@"d9d8d8");
    [ whiteView addSubview:line];
    UIButton*canleBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    canleBtn.frame=CGRectMake(10, 0, 50, 40);
    [canleBtn setTitleColor:MainColor forState:UIControlStateNormal];
    [canleBtn setTitle:@"取消" forState:UIControlStateNormal];
    canleBtn.titleLabel.font=F(13);
    [canleBtn bk_addEventHandler:^(id sender) {
         [self hideBox];

    } forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:canleBtn];

    UIButton*changeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    changeBtn.frame=CGRectMake(WindowWidth-50, 0, 50, 40);
    [changeBtn setTitleColor:MainColor forState:UIControlStateNormal];
    [changeBtn setTitle:@"确定" forState:UIControlStateNormal];
    changeBtn.titleLabel.font=F(13);
    [changeBtn bk_addEventHandler:^(id sender) {
        NSString *starTime=[NSString stringWithFormat:@"%@ %@",self.timeStr,self.hour];
        [self hideBox];
        
        [[LoadingView shareLoading] startAnimating];
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:self.uuid forKey:@"orderUuid"];
        [dic setObject:starTime forKey:@"evaluated_start_time"];
        [dic setObject:self.longitude forKey:@"longitude"];
        [dic setObject:self.latitude forKey:@"latitude"];
        
        [CClass HttpRequestTask:YES withUrl:@"warning_orderTake" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
            
            [[LoadingView shareLoading] stopAnimating];
            [CClass showLittleTimeMessage:@"接单成功" completion:nil];
            self.action(1);
        } onError:^(BaseModel *model) {
            
        }];
  
         
        
    } forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:changeBtn];

    _pickerView=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, WindowWidth, WindowHeight/3-40)];
    _pickerView.delegate=self;
    _pickerView.dataSource=self;
    _pickerView.backgroundColor =[UIColor whiteColor];
    _pickerView.showsSelectionIndicator=YES;
    [whiteView addSubview:_pickerView];
 

    
    
}
- (void) showBox{
    [self initView];
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    
}

- (void) hideBox{
    [self removeFromSuperview];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
    
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    
    return 35;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==0) {
        return _timeShowAr.count;
  
    }else
    {
        int selectTime= [pickerView selectedRowInComponent:0];
        NSMutableArray *hourAr=[_dataAr objectAtIndex:selectTime];
        return hourAr.count;

    }
    
    
}
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component==0) {
        return [_timeShowAr objectAtIndex:row];
    }else
    {
        int selectTime= [pickerView selectedRowInComponent:0];
        NSMutableArray *hourAr=[_dataAr objectAtIndex:selectTime];
        return [hourAr objectAtIndex:row];

    }
  
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component==0) {
        self.timeStr=[_timeAr objectAtIndex:row];
        [pickerView reloadComponent:1];
        int component0= [pickerView selectedRowInComponent:0];
        NSMutableArray *hourAr=[_dataAr objectAtIndex:component0];
        self.hour=[hourAr objectAtIndex:0];//默认第一行 小时


    }else
    {
        int selectTime= [pickerView selectedRowInComponent:0];
        NSMutableArray *hourAr=[_dataAr objectAtIndex:selectTime];
        self.hour=[hourAr objectAtIndex:row];

    }
    
}
- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",  nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

@end
